<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="openDB()">打开数据库</button>
    <button onclick="createDB()">新建数据库</button>
    <button onclick="insertOneDB()">插入一条数据</button>
    <button onclick="insertMultiDB()">插入多条数据</button>
    <button onclick="queryDB()">查询数据</button>
    <button onclick="updateDB()">更新数据</button>
    <div id="table"></div>

    <script>
        const dbName = 'users'
        const dbVersion = 1.0
        let db = null
        function openDB() {
            const request = indexedDB.open(dbName, dbVersion)
            request.onerror = function () {
                console.log('无法打开数据库');
            }

            request.onupgradeneeded = function (event) {
                db = event.target.result
                // 创建一个表
                const objectStore = db.createObjectStore('sex', { keyPath: 'id' })
                objectStore.createIndex('title', 'title', { unique: true })
            }

            request.onsuccess = function (event) {
                // console.log(event);
                db = event.target.result
                console.log(`数据库${db.name}已经开启`);
            }
        }
         //打开数据库



        function insertOneDB() {

            const transaction = db.transaction(['sex'], 'readwrite')
                .objectStore('sex')
                .add({ id: 1, title: '男生', author: '张三', createAt: Date.now() })

            transaction.onerror = function () {
                console.log('数据写入失败');
            }
            transaction.onsuccess = function () {
                console.log('数据写入成功');
            }
        }


         //往数据库里面插入一条数据
        function insertMultiDB(){
        }

       //往数据库里面插入多条数据
      function queryDB(){
            const transaction =db.transaction(['sex'],'readonly')
            const objectStore =transaction.objectStore('sex')

          
            const index=objectStore.index('title')

            const range=IDBKeyRange.only('女生')

            



            const req=objectStore.get(1)
            req.onerror=function(){
                console.log('查询失败')
            }
             req.onesucess = function () {
                console.log('req.result')
            }
        }



    </script>

</body>

</html>